﻿using System.Collections.Generic;
using System.Net;
using SocketCore.Network;

namespace SocketCore
{
    public class SocketServer
    {
        private NetworkConfig networkConfig = new NetworkConfig();
        private ISocketService socketService;

        public SocketServer()
        {
            this.networkConfig.Config("SocketServer.server.config");
            this.socketService = new SocketService();
        }

        public void SendMessageToSessions(IEnumerable<IoSession> sessions, byte[] message)
        {
            foreach(IoSession session in sessions)
                socketService.Send(session, message);
        }

        public void Start(INetworkHandler handler)
        {
            List<int> ports = networkConfig.Ports;
            for (int i = 0; i < ports.Count; i++)
            {
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, ports[i]);
                socketService.Bind(endPoint, handler);
            }
        }

        public void Start(NetworkHandlerChain handlerChain)
        {
            List<int> ports = networkConfig.Ports;
            for (int i = 0; i < ports.Count; i++)
            {
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, ports[i]);
                socketService.Bind(endPoint, handlerChain);
            }
        }

        public void Stop()
        {
            SocketService.UnBindAll();
        }

        public void Stop(int port)
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
            socketService.UnBind(endPoint);
        }

        public ISocketService SocketService
        {
            get
            {
                return this.socketService;
            }
        }
    }
}
